import { ThemeContext } from "@/contexts/ThemeContext";
import { html } from "@codemirror/lang-html";
import { json } from "@codemirror/lang-json";
import { Typography } from "@mui/material";
import { Box } from "@mui/system";
import { githubDark, githubLight } from "@uiw/codemirror-theme-github";
import CodeMirror, { Extension } from '@uiw/react-codemirror';
import { useContext, useMemo } from "react";


const CodeMirrorWrapper = ({
    value,
    onChange,
    label,
    height,
    language,
    readOnly,
    placeholder,
}: {
    value: string;
    onChange: (value: string) => void;
    label: string;
    height?: string;
    language?: 'html' | 'json' | 'text';
    readOnly?: boolean,
    placeholder?: string,
}) => {
    // 主题色
    const { mode } = useContext(ThemeContext);

    // 根据language参数选择不同的语言扩展
    const getLanguageExtension = () => {
        if (language === 'html') {
            return html();
        } else if (language === 'json') {
            return json();
        }
        return json();
    };

    // 组合所有扩展
    const extensions: Extension[] = useMemo(() => {
        const exts: Extension[] = [getLanguageExtension()];
        return exts;
    }, [getLanguageExtension]);

    return (
        <Box sx={{ width: '100%', display: 'flex', flexDirection: 'column' }}>
            <Typography variant="subtitle1" sx={{ mb: 1 }}>
                {label}
            </Typography>
            <Box sx={{
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 1,
                overflow: 'hidden',
                height: height || 'auto'
            }}>
                <CodeMirror
                    value={value}
                    height={height || '300px'}
                    theme={mode === 'dark' ? githubDark : githubLight}
                    onChange={onChange}
                    style={{ fontSize: '14px' }}
                    extensions={extensions}
                    readOnly={readOnly}
                    placeholder={placeholder}
                />
            </Box>
        </Box>
    );
};

export default CodeMirrorWrapper;